﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace CourseRecommend 
{
    public static class RecommendMe
    {
        public static List<string> recommendedList = new List<string>();
        public static List<string> historyList = new List<string>();
        public static List<string> prereqList = new List<string>();
        public static List<string> orderedCurriculum = new List<string>();
        public static List<string> creditList = new List<string>();
        public static List<string> classNames = new List<string>();
        public static List<string> tempHistoryList = new List<string>();
        public static List<string> prereqNotTaken = new List<string>();
        public static List<string> prereqsToTake = new List<string>();
        public static string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Catalog.mdf;Integrated Security=True;User Instance=True";
        public static int semesterCount = 0;
        
        private static int counter = -1;
        private static int i = 0;
        private static int classCounter = 0;
        private static int globalCounter = 0;
        private static string loopChecker = "";
        private static int countofUnrecommendedLookedAt = 0;
       
        public static int currentSemester = HomeForm.semInt;


        public static void recommendSchedule()
        {
            // look at first class in curriculum and see if it has been taken
            // if not then check for semester offered and prerequisites(if met recommend, if not recommend prerequisite for that class)
            //if not offered move to next class in curiculum
            //check difficulty 
            // recommend for whole semester
            // assume all classes recommended will have been taken and passed
            //use this assumption and continue recommending classes 
            counter = -1;
            i = 0;
            classCounter = 0;
            globalCounter = 0;
            loopChecker = "";

            getHistory();
            getOrderedList();
            // add the starting semester to the recommend list
            recommendedList.Add(HomeForm.startSem);
            int curriculumnSize = orderedCurriculum.Count;
            string classID = orderedCurriculum[0];
            currentSemester = HomeForm.semInt;
            string[] semArray = new string[3] { "Spring", "Summer", "Fall" };
         
            int creditCount = 0;

            foreach (string item in historyList)
                tempHistoryList.Add(item);

            int addToHistoryCounter = HomeForm.semesterHours / 3;
            for (globalCounter = 0; globalCounter < curriculumnSize; globalCounter++)
            {
                classID = findNextUntakenClassFromCurriculum(classID);
                if(classID.Equals("Finish"))
                {
                    break;
                }
                // prevent looping at end of recommendation when large semester hours are allowed
                if(creditCount >=16)
                    if (CountUnrecommendedClasses() <= 8)
                    {
                        creditCount = 20;
                    }
                foreach (string item in selectPrerequisiteIfNeeded(classID))
                {
                    if (!recommendedList.Contains(item))
                    {
                        recommendedList.Add(item);
                        //add the credits of the current class to a creditlist
                        creditList.Add(getCredits(item));
                        creditCount = Convert.ToInt32(getCredits(item)) + creditCount;
                    }
                        if (currentSemester == 2)
                        {
                            if (creditCount >= 6 && CountUnrecommendedClasses() != 0)
                            {
                                calculateSemester();
                                semesterCount++;
                                creditCount = 0;
                            }
                        }

                        else if (creditCount >= HomeForm.semesterHours && CountUnrecommendedClasses()!=0)
                        {
                            semesterCount++;
                            calculateSemester();
                            creditCount = 0;
                        }

                        classCounter++;
                        // check to see if a whole semester has been recommended and if it has add all classes tpo now to the temphistory
                        //if (classCounter >= addToHistoryCounter)
                        //{
                        //    tempHistoryList.AddRange(recommendedList);
                        //    classCounter = 0;
                        //    globalCounter = 0;
                        //}
                    }
                
                prereqsToTake.Clear();
            }
            getNames();
        }

        public static void calculateSemester()
        {
            if (currentSemester == 1)
            {
                if (HomeForm.summer)
                {
                    currentSemester++;
      //              globalCounter = 0;
                    recommendedList.Add("\r\n CS Summer Semester \r\n");
                    tempHistoryList.AddRange(recommendedList);
                    classCounter = 0;
                    globalCounter = 0;
                }
                else
                {
                    currentSemester = 3;
                    recommendedList.Add(" \r\n  Fall Semester \r\n");
    //                globalCounter = 0;
                    tempHistoryList.AddRange(recommendedList);
                    classCounter = 0;
                    globalCounter = 0;
                }

            }
            else if (currentSemester == 2)
            {
                currentSemester = 3;
                recommendedList.Add(" \r\n  Fall Semester \r\n");
  //              globalCounter = 0;
                tempHistoryList.AddRange(recommendedList);
                classCounter = 0;
                globalCounter = 0;
            }
            else if (currentSemester == 3)
            {
                currentSemester = 1;
                recommendedList.Add(" \r\n  Spring Semester \r\n");
   //             globalCounter = 0;
                tempHistoryList.AddRange(recommendedList);
                classCounter = 0;
                globalCounter = 0;
            }

        }
        

        
        public static string findNextUntakenClassFromCurriculum(string ClassIdentification)
        {
            while (historyList.Contains(ClassIdentification) || tempHistoryList.Contains(ClassIdentification) || recommendedList.Contains(ClassIdentification) && globalCounter < orderedCurriculum.Count)
            {
                if (globalCounter == orderedCurriculum.Count -1)
                {
                    globalCounter = -1;
                    if (checkForCompletionOfRecommendation())
                    {
                        globalCounter = 0;
                        break;
                    }
                }
                globalCounter++;
                ClassIdentification = orderedCurriculum[globalCounter]; 
            }
            ClassIdentification = orderedCurriculum[globalCounter];
            if (checkForCompletionOfRecommendation())
                ClassIdentification = "Finish";
            int tempcount = CountUnrecommendedClasses();
            
            if (tempcount <= 3 && !tempHistoryList.Contains(ClassIdentification))
            {
                countofUnrecommendedLookedAt++;
                if (currentSemester == 1 && countofUnrecommendedLookedAt > tempcount +2 && ! checkForCompletionOfRecommendation())
                {
                    currentSemester = 3;
                    recommendedList.Add(" \r\n Fall Semester \r\n");
                    countofUnrecommendedLookedAt = 0;
                }
                else if (currentSemester == 3 && countofUnrecommendedLookedAt > tempcount+2 && ! checkForCompletionOfRecommendation())
                {
                    currentSemester = 1;
                    recommendedList.Add(" \r\n Spring Semester \r\n");
                    countofUnrecommendedLookedAt = 0;
                }
                else if (currentSemester == 2 && countofUnrecommendedLookedAt > tempcount+2 && !checkForCompletionOfRecommendation())
                {
                    currentSemester = 1;
                    recommendedList.Add(" \r\n Spring Semester \r\n");
                    countofUnrecommendedLookedAt = 0;
                }

            }
                return ClassIdentification;

        }



        public static List<string> selectPrerequisiteIfNeeded(string classIdentification)
        {

            if (!havePrereq(classIdentification))
            {

                foreach (string item in getPrereqNotTaken(classIdentification))
                {
                    if (!prereqNotTaken.Contains(item))
                    {
                        prereqNotTaken.Add(item);
                        counter++;
                        classIdentification = prereqNotTaken[counter];
                    }
                    else
                        classIdentification = item;
                }
                
                if (havePrereq(classIdentification) && isOfferedThisSemester(classIdentification))
                {
                    prereqsToTake.Add(classIdentification);
                    return prereqsToTake;
                }
                else
                {

                    selectPrerequisiteIfNeeded(classIdentification);
                }

            }
            else if (!historyList.Contains(classIdentification))
            {
                if (!tempHistoryList.Contains(classIdentification))
                {
                    if (isOfferedThisSemester(classIdentification))
                    {
                        if(!prereqsToTake.Contains(classIdentification))
                        prereqsToTake.Add(classIdentification);
                    }
                }
            }

            return prereqsToTake;
        }

        public static Boolean isOfferedThisSemester(string classIdentification)
        {
            SqlConnection myConnection = new SqlConnection(connectionString);

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            SqlCommand command = new SqlCommand("SELECT SemesterOffered FROM [CatalogTable] WHERE ClassId =  @CID", myConnection);
            command.Parameters.AddWithValue("@CID", classIdentification);
            SqlDataReader reader = null;
            reader = command.ExecuteReader();
            //loop through all records 
            bool moreResults = true;
            bool returnBool = false;
            while (moreResults)
            {
                while (reader.Read())
                {
                    if (currentSemester == 1)
                    {
                        if (reader["SemesterOffered"].ToString().Equals("S") | reader["SemesterOffered"].ToString().Equals("SSF") | 
                        reader["SemesterOffered"].ToString().Equals("SF"))
                        {
                            returnBool = true;
                        }

                    }
                    else if (currentSemester == 2)
                    {
                        if (reader["SemesterOffered"].ToString().Equals("SSF"))
                        {
                            returnBool = true;
                        }

                    }
                    else if (currentSemester == 3)
                    {
                        if (reader["SemesterOffered"].ToString().Equals("F") | reader["SemesterOffered"].ToString().Equals("SSF") |
                        reader["SemesterOffered"].ToString().Equals("SF"))
                        {
                            returnBool = true;
                        }

                    }
                    else returnBool = false;
                    if (loopChecker.Equals(classIdentification))
                    {
                        breakOutofLoop(classIdentification);
                    }
                    moreResults = reader.NextResult();
                }
            }
            reader.Close();
            myConnection.Close();
            return returnBool;
        }



        //passed tests
        public static Boolean havePrereq(string classIdentification)
        {
            SqlConnection myConnection = new SqlConnection(connectionString);

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            SqlCommand command = new SqlCommand("SELECT Prerequisite, Prerequisite2, OrPrereq1, OrPrereq2 FROM [CatalogTable] WHERE ClassId =  @CID", myConnection);
            command.Parameters.AddWithValue("@CID", classIdentification);
            SqlDataReader reader = null;
            reader = command.ExecuteReader();
            //loop through all records comparing each one with the classID that was passed

            bool rVal = false;
            bool moreResults = true;
            int size = tempHistoryList.Count;
            while (moreResults)
            {
                while (reader.Read())
                {
                    if ((historyList.Contains(reader["Prerequisite"].ToString()) | tempHistoryList.Contains(reader["Prerequisite"].ToString())) &&
                        (historyList.Contains(reader["Prerequisite2"].ToString()) | tempHistoryList.Contains(reader["Prerequisite2"].ToString())))
                    {
                        rVal = true;
                    }
                    else if ((historyList.Contains(reader["OrPrereq1"].ToString()) | tempHistoryList.Contains(reader["OrPrereq1"].ToString()))
                         || (historyList.Contains(reader["OrPrereq2"].ToString())) | (tempHistoryList.Contains(reader["OrPrereq2"].ToString())))
                    {
                        rVal = true;
                    }
                    else if (String.Compare(reader["Prerequisite"].ToString(), "and") == 0)
                    {
                        if (andOfOrs(classIdentification))
                            rVal = true;
                        else rVal = false;
                    }
                    else rVal = false;
                }
                moreResults = reader.NextResult();
            }
            reader.Close();
            myConnection.Close();
            return rVal;
        }

        // passed testing cases
        public static Boolean andOfOrs(string cID)
        {
            SqlConnection myConnection = new SqlConnection(connectionString);

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            SqlCommand command = new SqlCommand("SELECT Prerequisite, Prerequisite2, Prerequisite3, OrPrereq1, OrPrereq2 FROM [CatalogTable] WHERE ClassId =  @CID", myConnection);
            command.Parameters.AddWithValue("@CID", cID);
            SqlDataReader reader = null;
            reader = command.ExecuteReader();
            //loop through all records 
            bool moreResults = true;
            bool rVal = false;
            while (moreResults)
            {
                while (reader.Read())
                {
                    if ((historyList.Contains(reader["Prerequisite"].ToString()) | tempHistoryList.Contains(reader["Prerequisite"].ToString()))
                        && String.Compare(reader["Prerequisite2"].ToString(), "and") == 0 &&
                        (historyList.Contains(reader["Prerequisite3"].ToString()) | historyList.Contains(reader["OrPrereq1"].ToString())
                        | historyList.Contains(reader["OrPrereq2"].ToString()) | tempHistoryList.Contains(reader["Prerequisite3"].ToString()) | tempHistoryList.Contains(reader["OrPrereq1"].ToString())
                        | tempHistoryList.Contains(reader["OrPrereq2"].ToString())))
                    {
                        rVal = true;
                    }
                    else
                    {
                        rVal = false;
                    }
                }
                moreResults = reader.NextResult();
            }
            reader.Close();
            myConnection.Close();
            return rVal;

        }


        public static List<string> getPrereqNotTaken(string classIdentification)
        {
            SqlConnection myConnection = new SqlConnection(connectionString);

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            SqlCommand command = new SqlCommand("SELECT Prerequisite, Prerequisite2, Prerequisite3, OrPrereq1, OrPrereq2 FROM [CatalogTable] WHERE ClassId =  @CID", myConnection);
            command.Parameters.AddWithValue("@CID", classIdentification);
            SqlDataReader reader = null;
            reader = command.ExecuteReader();
            //loop through all records 
            bool moreResults = true;
            List<string> prereqs = new List<string>();
            while (moreResults)
            {
                while (reader.Read())
                {
                    if (!historyList.Contains(reader["Prerequisite"].ToString()) && !tempHistoryList.Contains(reader["Prerequisite"].ToString()))
                    {
                        prereqs.Add(reader["Prerequisite"].ToString());
                    }
                    if (!historyList.Contains(reader["Prerequisite2"].ToString()) && String.Compare(reader["Prerequisite2"].ToString(), "and") != 0
                        && !tempHistoryList.Contains(reader["Prerequisite2"].ToString()))
                    {
                        prereqs.Add(reader["Prerequisite2"].ToString());
                    }
                    //if AND of ORs
                    if (String.Compare(reader["Prerequisite2"].ToString(), "and") == 0)
                    {
                        if (!historyList.Contains(reader["Prerequisite3"].ToString()) && !tempHistoryList.Contains(reader["Prerequisite3"].ToString()))
                        {
                            prereqs.Add(reader["Prerequisite3"].ToString());
                        }
                        else if (!historyList.Contains(reader["OrPrereq1"].ToString()) && !tempHistoryList.Contains(reader["OrPrereq1"].ToString()))
                        {
                            prereqs.Add(reader["OrPrereq1"].ToString());
                        }
                        else if (!historyList.Contains(reader["OrPrereq2"].ToString()) && !tempHistoryList.Contains(reader["OrPrereq2"].ToString()))
                        {
                            prereqs.Add(reader["OrPrereq2"].ToString());
                        }
                    }
                }
                moreResults = reader.NextResult();
            }
            reader.Close();
            myConnection.Close();
            return prereqs;
        }


        public static Boolean preReq(string cID)
        {
            SqlConnection myConnection = new SqlConnection(connectionString);

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            // select and compare up to three prereqs
            // For cases such as Math 161 OR Math155 OR.......
            SqlCommand command = new SqlCommand("SELECT Prerequisite, OrPrereq1, OrPrereq2 FROM [CatalogTable] WHERE ClassId =  @CID", myConnection);
            command.Parameters.AddWithValue("@CID", cID);
            SqlDataReader reader = null;
            reader = command.ExecuteReader();
            //loop through all records comparing each one with the classID that was passed
            int i = 0;
            bool moreResults = true;
            bool rVal = false;
            int size = tempHistoryList.Count;
            while (moreResults)
            {
                while (reader.Read())
                {
                    if (historyList.Contains(reader["Prerequisite"].ToString()) | String.Compare(reader["Prerequisite"].ToString(), "666") == 0 | historyList.Contains(reader["OrPrereq1"].ToString()) | historyList.Contains(reader["OrPrereq2"].ToString())
                        | tempHistoryList.Contains(reader["Prerequisite"].ToString()) | tempHistoryList.Contains(reader["OrPrereq1"].ToString()) | tempHistoryList.Contains(reader["OrPrereq2"].ToString()))
                    {
                        rVal = true;
                    }
                    else
                    {
                        rVal = false;
                    }
                    if (size - 4 >= 0)
                    {

                        for (i = size - 4; i < size; i++)
                        {
                            if (tempHistoryList[i].Equals(reader["Prerequisite"].ToString()) | tempHistoryList[i].Equals(reader["OrPrereq1"].ToString()) | tempHistoryList[i].Equals(reader["OrPrereq2"].ToString()))
                                //                            MessageBox.Show(tempHistoryList[i],i.ToString());
                                rVal = false;
                        }
                    }
                }
                moreResults = reader.NextResult();
            }
            reader.Close();
            myConnection.Close();
            return rVal;

        }
        // check prereq2 and or prereqs.
        public static Boolean preReq2(string cID)
        {
            SqlConnection myConnection = new SqlConnection(connectionString);

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            SqlCommand command = new SqlCommand("SELECT Prerequisite, Prerequisite2, OrPrereq1, OrPrereq2 FROM [CatalogTable] WHERE ClassId =  @CID", myConnection);
            command.Parameters.AddWithValue("@CID", cID);
            SqlDataReader reader = null;
            reader = command.ExecuteReader();
            //loop through all records comparing each one with the classID that was passed
            bool moreResults = true;
            bool rVal = false;
            int size = tempHistoryList.Count;
            int i = 0;
            while (moreResults)
            {
                while (reader.Read())
                {
                    if (historyList.Contains(reader["Prerequisite2"].ToString()) | historyList.Contains(reader["OrPrereq1"].ToString()) | historyList.Contains(reader["OrPrereq2"].ToString())
                       | tempHistoryList.Contains(reader["Prerequisite2"].ToString()) | tempHistoryList.Contains(reader["OrPrereq1"].ToString()) | tempHistoryList.Contains(reader["OrPrereq2"].ToString()))
                    {
                        rVal = true;
                    }
                    else
                    {
                        rVal = false;
                    }
                    if (size - 4 >= 0)
                    {

                        for (i = size - 4; i < size; i++)
                        {
                            if (tempHistoryList[i].Equals(reader["Prerequisite2"].ToString()) | tempHistoryList[i].Equals(reader["OrPrereq1"].ToString()) | tempHistoryList[i].Equals(reader["OrPrereq2"].ToString()))
                                //                              MessageBox.Show(tempHistoryList[i], i.ToString());
                                rVal = false;
                        }
                    }
                }
                moreResults = reader.NextResult();
            }
            reader.Close();
            myConnection.Close();
            return rVal;

        }


        public static string getCredits(string classID )
        {
            SqlConnection myConnection = new SqlConnection(connectionString);
            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            SqlCommand command = new SqlCommand("SELECT Credits FROM [CatalogTable] WHERE ClassId =  @CID", myConnection);
            command.Parameters.AddWithValue("@CID", classID);
            SqlDataReader reader = null;
            string returnCredit = "";
            reader = command.ExecuteReader();
            bool moreResults = true;
            while (moreResults)
            {
                while (reader.Read())
                {
                    returnCredit =(reader["Credits"].ToString());
                }
                moreResults = reader.NextResult();

                reader.Close();
            }
            myConnection.Close();
            return returnCredit;
        }

     
        public static void getNames()
        {
            SqlConnection myConnection = new SqlConnection(connectionString);
            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            int i = 0;
            int size = recommendedList.Count;
            for (i = 0; i < size; i++)
            {
                string classID = recommendedList[i];
                SqlCommand command = new SqlCommand("SELECT Name,Subject, Level, HistoricDifficulty FROM [CatalogTable] WHERE ClassId =  @CID", myConnection);
                command.Parameters.AddWithValue("@CID", classID);
                SqlDataReader reader = null;
                reader = command.ExecuteReader();
                bool moreResults = true;
                while (moreResults)
                {
                    try
                    {
                        while (reader.Read())
                        {
                            classNames.Add(reader["Subject"].ToString() + " " + reader["Level"].ToString() + " " + "( " + reader["Name"].ToString() + " )      " + reader["HistoricDifficulty"].ToString());
                        }
                        moreResults = reader.NextResult();
                    }
                    catch (Exception e)
                    {
                        classNames.Add("\r\n");
                        classNames.Add(recommendedList[i]);
                        classNames.Add("\r\n");
                    }
                }
                reader.Close();
            }
            myConnection.Close();
        }

        public static double calculateDifficulty()
        {
            //calculate difficulty of semester
            double dRating = 0.0;
            return dRating;
        }

        //public static string getCurrentSemester()
        //{
        //    int startingSemester = HomeForm.semInt;
        //    string[] semArray = new string[3] { "Spring", "Summer", "Fall" };

        //}
        //tested and working
        public static void getHistory()
        {
            string studentID = LoginForm.loginName;
            SqlConnection myConnection = new SqlConnection(connectionString);

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            SqlCommand command = new SqlCommand("SELECT * FROM [StudentClassRecords] WHERE RecordsStudentID =  @SID", myConnection);
            command.Parameters.AddWithValue("@SID", studentID);
            SqlDataReader reader = null;
            reader = command.ExecuteReader();
            bool moreResults = true;
            while (moreResults)
            {
                while (reader.Read())
                {
                    if(! historyList.Contains(reader["RecordsClassId"].ToString()))
                    historyList.Add(reader["RecordsClassId"].ToString());

                }
                moreResults = reader.NextResult();
            }
            myConnection.Close();
        }

        //tested and working 
        public static void getOrderedList()
        {
            SqlConnection myConnection = new SqlConnection(connectionString);

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            SqlCommand command = new SqlCommand("SELECT * FROM [CS_Science_Curriculum]", myConnection);
            SqlDataReader reader = null;
            reader = command.ExecuteReader();
            bool moreResults = true;
            while (moreResults)
            {
                while (reader.Read())
                {
                    orderedCurriculum.Add(reader["ClassID"].ToString());

                }
                moreResults = reader.NextResult();
            }
            myConnection.Close();
        }


        public static void breakOutofLoop(string classidentification)
        {
            SqlConnection myConnection = new SqlConnection(connectionString);

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            SqlCommand command = new SqlCommand("SELECT SemesterOffered FROM [CatalogTable] WHERE ClassId =  @CID", myConnection);
            command.Parameters.AddWithValue("@CID", classidentification);
            SqlDataReader reader = null;
            string semesterString = "";
            reader = command.ExecuteReader();
            bool moreResults = true;
            while (moreResults)
            {
                while (reader.Read())
                {
                    semesterString = (reader["SemesterOffered"].ToString());

                }
                moreResults = reader.NextResult();
            }
            switch (semesterString)
            {
                case "S":
                    currentSemester = 1;
                    recommendedList.Add(" \r\n Spring Semester \r\n");
                    recommendedList.Add(classidentification);
                    break;
                case "F":
                    currentSemester = 3;
                    recommendedList.Add(" \r\n Fall Semester \r\n");
                    recommendedList.Add(classidentification);
                    break;
            }

            myConnection.Close();
        }

        public static bool checkForCompletionOfRecommendation()
        {
            Boolean returnBoolean = false;
            foreach(string item in orderedCurriculum)
             {
                if (recommendedList.Contains(item) || historyList.Contains(item))
                {
                    returnBoolean = true;
                }
                else
                {
                    returnBoolean = false;
                    break;
                }
            }
            return returnBoolean;
        }

        public static int CountUnrecommendedClasses()
        {
            List<string> leftovers = new List<string>();
            
            int leftoverCount = 0;
            int numCheck;
            foreach (string item in orderedCurriculum)
            {
                if (int.TryParse(item, out numCheck))
                {
                    if (! recommendedList.Contains(item) && ! leftovers.Contains(item))
                    {
                        leftovers.Add(item);
                    }
                }
            }
            leftoverCount = leftovers.Count;
            if (leftoverCount > 4)
                leftovers.Clear();
            return leftoverCount;
        }
    }
   }

